package com.vcms.controller.customer;

import com.vcms.controller.storemanagement.StoreController;
import com.vcms.entity.store.CashStore;
import com.vcms.entity.store.item.CashStoreItem;
import com.vcms.entity.store.itemtype.Coin;
import com.vcms.exception.VMCSException;
import com.vcms.utility.formatter.MoneyFormatter;
import com.vmcs.entity.store.item.iterator.DenominationIterator;

public class ChangeGiver {
	
	private TransactionController transactionController;
	
	public ChangeGiver(TransactionController transactionController){
		this.transactionController = transactionController;
	}
	
	
	public void resetChange(){
		transactionController.getCustomerPanel().getCollectCoin().setValue(MoneyFormatter.toMoney(0));
	}
	
	
	public void displayChangeStatus(){
		boolean noChange = true;
		CashStore cashStore = (CashStore)transactionController.getMainControler().getStoreController().getStore(StoreController.CASH);
		for(int i=0;i<=cashStore.getStoreSize()-1;i++){
			CashStoreItem cashStoreItem;
			try {
				cashStoreItem = (CashStoreItem)cashStore.getStoreItem(i);
				if(cashStoreItem.getQuantity()>0){
					noChange = false;
					break;
				}
			} catch (VMCSException e) {
				e.printStackTrace();
			}
		}
		transactionController.getCustomerPanel().getNoChangeAvailableWarningLabel().setState(noChange);
	}
	
	public boolean giveChange(float changeRequired) throws VMCSException{

		CashStore cashStore = (CashStore)transactionController.getMainControler().getStoreController().getStore(StoreController.CASH);
		int changeReturned = 0;
		
		DenominationIterator denominationIterator = new DenominationIterator(cashStore.getItems());
		while (denominationIterator.isDone() == false) {
			int numberOfCoins = 0;
			
			CashStoreItem cashStoreItem = (CashStoreItem) denominationIterator.current();
			Coin coin =  (Coin)cashStoreItem.getContent();
			int value = coin.getValue();
			
			while((changeReturned + value) <= changeRequired){
				if(cashStoreItem.getQuantity() > numberOfCoins ){
					numberOfCoins++;
					changeReturned = changeReturned + value;
				} else
					break;
			}
			
			// change returned is within the change required
			if(numberOfCoins > 0) {
				this.transactionController.getMainControler().getMachinaryController().giveChange(denominationIterator.getCurrent(), numberOfCoins);
			}
			denominationIterator.next();
		}
		transactionController.getCustomerPanel().getCollectCoin().setValue(MoneyFormatter.toMoney(changeReturned));
		transactionController.getCustomerPanel().getNoChangeAvailableWarningLabel().setState((changeReturned < changeRequired));
		
		return true;
	}

}
